#include "DefenseCannon.h"
#include "Grenade.h"
#include "RSManager.h"
#include "Sprite.h"
#include "Box.h"
#include <time.h>
#include <list>


DefenseCannon::DefenseCannon(Box* box) : Object(box, ObjDefenseCannon)
{

}


DefenseCannon::~DefenseCannon(void)
{

}

void DefenseCannon::update()
{	
	if(_isALive)
	{
		this->delay += GAME_TIME;
		if(_blood == 0)
		{
			_sprite = _explode;
			if(delay > 100)
			{
				delay = 0;
				_sprite->Next();
				if(_sprite->GetCurrentIndex() == 3)
					_isALive = false;
			}
		}
		else
		{
			if (delay > 550)
			{
				delay = 0;		
				if(_sprite->GetCurrentIndex() == 1)
					shoot();
				_sprite->Next();							
			}
		}
	}
	std::list<Grenade*>::iterator gr = listGrenadeUpdate.begin();
	while (gr != listGrenadeUpdate.end())
	{
		if((*gr)->isAlive())
			(*gr++)->update();
		else
		{			
			listGrenadeInit.push_back(*gr);
			listGrenadeUpdate.remove(*gr++);	
		}
	}			
}

void DefenseCannon::render()
{
	_sprite->Render(_box->_position);
	for(Grenade* gr : listGrenadeUpdate)
		if(gr->isAlive())
			gr->render();
}

void DefenseCannon::shoot()
{
	if(listGrenadeInit.size() != 0)
	{
		Grenade* grenade = listGrenadeInit.front();
		int v = 2 + rand() % 3;
		grenade->process(ObjGrenade, _box->_position - D3DXVECTOR2(10, 4), v);
		listGrenadeUpdate.push_back(grenade);
		listGrenadeInit.remove(grenade);
	}	
}

void DefenseCannon::init()
{	
	_cannon = RSManager::getInstance()->getSprite(DEFENSE_CANNON);
	_explode = RSManager::getInstance()->getSprite(EXPLODE_CANNON);
	_sprite = _cannon;
	for(int i = 0; i < 5; i++)
	{						
		Grenade* grenade = new Grenade();
		grenade->init();		
		listGrenadeInit.push_back(grenade);
	}
	delay = 0;
	_blood = 16;
	_isALive = true;
	_box->_size = _sprite->getRenderSize();
}

void DefenseCannon::setIndexOfSprite(int index)
{
	_sprite->Reset(index);
}

void DefenseCannon::decreaseBlood(int unit)
{
	if(_blood <= 0)
		_blood = 0;
	else
		_blood -= unit;
}
